import { NextRequest } from 'next/server';
import { prisma } from '@/lib/prisma';
import { verifyToken, extractTokenFromHeader } from './jwt';
import type { User } from '@prisma/client';
import { UserRole } from '@/constants/user';

export interface AuthResult {
  success: boolean;
  user?: User;
  error?: string;
}

// 验证请求中的JWT token
export async function authenticateRequest(request: NextRequest, requiredRole: UserRole = UserRole.NORMAL_USER): Promise<AuthResult> {
  try {
    const authHeader = request.headers.get('authorization');
    const token = extractTokenFromHeader(authHeader);

    if (!token) {
      return {
        success: false,
        error: '缺少认证token',
      };
    }

    // 验证token
    const payload = verifyToken(token);
    if (!payload || !payload.userId) {
      return {
        success: false,
        error: '无效的token',
      };
    }

    // 从数据库获取用户信息
    const user = await prisma.user.findUnique({
      where: { id: payload.userId },
    });

    if (!user) {
      return {
        success: false,
        error: '用户不存在',
      };
    }

    if (user.status !== 1) {
      return {
        success: false,
        error: '账号已被禁用',
      };
    }

    // 检查用户权限
    if (user.role > requiredRole) {
      return {
        success: false,
        error: '权限不足',
      };
    }

    return {
      success: true,
      user,
    };
  } catch (error) {
    console.error('认证失败:', error);
    return {
      success: false,
      error: '认证失败',
    };
  }
}

// 检查用户权限
export function checkPermission(user: User, requiredRole: number): boolean {
  // 超级管理员拥有所有权限
  if (user.role === 1) {
    return true;
  }
  return user.role <= requiredRole;
}